package cc.wanforme.st.server.authen.anno;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Supplier;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public class HasPermissionAuthorizationManager implements AuthorizationManager<MethodInvocation>{

	@Override
	public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation mi) {
		Authentication auth = authentication.get();
		Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
		
		// 寻找注解
		HasPermission hasPermission = AnnotationUtils.findAnnotation(mi.getMethod(), HasPermission.class);
		if(hasPermission == null) { // 不存在此情况
			return new AuthorizationDecision(false);
		}
		
		// 筛选权限
		boolean match = authorities.stream()
			.anyMatch(e -> Objects.equals(e.getAuthority(), hasPermission.value()));

		return new AuthorizationDecision(match);
	}

}
